// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();

  cloud.updateConfig({
    env: wxContext.ENV == "local" ? "test-go5gy" : wxContext.ENV
  });

  const db = cloud.database();

  const {
    name,
    author,
    read_url,
    cover,
    source_id,
    url,
    latest_chapter_url
  } = event;

  const res = await db
    .collection("bookshelfs")
    .where({
      _openid: wxContext.OPENID,
      name,
      author
    })
    .get();

  const sourceName = await db
    .collection("book_sources")
    .doc(source_id)
    .field({ name: true })
    .get();

  if (res.data.length == 0) {
    // 新添加书架
    const add = await db.collection("bookshelfs").add({
      data: {
        name,
        author,
        cover,
        // 源
        source_id,
        // 书籍链接
        read_url,
        // 阅读链接
        url,
        // 阅读章节的第几页
        page: 0,
        // 最新章节 用于以后判断是否更新
        latest_chapter_url,
        // 加入时间，以供首页的排序
        read_time: new Date().getTime(),
        // 源名
        source_name: sourceName.data.name,
        _openid: wxContext.OPENID
      }
    });
    if (add.errMsg == "collection.add:ok") {
      return { errMsg: "ok", data: { _id: add._id } };
    } else {
      return { errMsg: add.errMsg };
    }
  } else if (res.data.length == 1) {
    // 添加备用源
    const {
      _id,
      source_id: _source_id,
      read_url: _read_url,
      other_sources = []
    } = res.data[0];
    if (_source_id == source_id && _read_url == read_url) {
      return { errMsg: "该书籍已在书架", data: res.data[0] };
    }
    if (
      other_sources.some(
        os => os.source_id == source_id && os.read_url == read_url
      )
    ) {
      return { errMsg: "源已在书籍备用源中", data: res.data[0] };
    }

    other_sources.push({
      source_id,
      read_url,
      source_name: sourceName.data.name
    });
    const update_res = await db
      .collection("bookshelfs")
      .doc(_id)
      .update({
        data: {
          other_sources: other_sources
        }
      });
    if (update_res.stats && update_res.stats.updated == 1) {
      return { errMsg: "ok", data: { other_sources, _id } };
    }
    console.log(update_res);
    // if(update_res.errMsg){}
  } else {
    return {
      errMsg: "该书籍已在书架",
      data: res.data[0]
    };
  }
};
